﻿using ClientAppraise.Controls;
using ClientAppraise.Views.Pages.Corpus.CorpusAdorn.Admin;
using ClientAppraise.Views.Pages.Corpus.CorpusAdornType.Controls;
using ClientDao.Corpus;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ShareCode.Dto;
using ShareCode.Dto.Corpus;
using ShareCode.Entity.Corpus;
using ShareCode.KeyValue.Corpus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using Wpf.Ui.Controls;

namespace ClientAppraise.ViewModels.Pages.Corpus.CorpusAdorn.Admin
{
    public partial class IndexViewModel(CorpusAdornDal dal) : ObservableObject
    {
        CorpusAdornDal Dal = dal;

        [ObservableProperty]
        Type tEnumCorpusAdornType = typeof(EnumCorpusAdornType);

        [ObservableProperty]
        List<CorpusAdornWithTypeDto>? viewData;

        [ObservableProperty]
        private CorpusAdornWithTypeDto? selectedItems;
        partial void OnSelectedItemsChanged(CorpusAdornWithTypeDto? value)
        {
            IsEnabled = value != null;
        }

        [ObservableProperty]
        private bool isEnabled = false;

        [ObservableProperty]
        private string? selectedTypeTitles;
        partial void OnSelectedTypeTitlesChanged(string? value)
        {
            pagingDto = new PagingDto { PageSize = 999999 };
        }

        [ObservableProperty]
        private string? searchTitle;
        partial void OnSearchTitleChanged(string? value)
        {
            pagingDto = new PagingDto { PageSize = 999999 };
        }

        private List<long> selectedTypeIds = [];

        PagingDto pagingDto = new PagingDto { PageSize = 999999 };


        [RelayCommand]
        public async Task Search()
        {
            await RefreshData();
        }

        [RelayCommand]
        public void Add()
        {
            App.MyNavigation.NavigateWithHierarchy(typeof(NewPage));
        }

        [RelayCommand]
        public void Edit()
        {
            App.MyNavigation.NavigateWithHierarchy(typeof(NewPage), new ClientInfrastructure.Dto.PageParameterDto() { Model = SelectedItems!, Do = ClientInfrastructure.Dto.PageParameterDtoDo.Update });
        }

        [RelayCommand]
        public async Task DeleteAsync()
        {
            if (SelectedItems != null && await new ZxMessageBox().ConfirmAsync("确定要删除选中项？") == Wpf.Ui.Controls.MessageBoxResult.Primary)
            {
                var reslut = await App.MyContentDialog.ShowRingLoadingAsync(async () =>
                {
                    try
                    {
                        ResultDto<bool> result;

                        if (SelectedItems.IsDelete == 1)
                        {
                            result = await Dal.UnLogicDeleteAsync(SelectedItems.Id);
                        }
                        else
                        {
                            result = await Dal.LogicDeleteAsync(SelectedItems.Id);

                        }
                        if (result != null && result.Success && result.Data)
                        {
                            App.MySnackbar.Success("成功操作");
                        }
                        else
                        {
                            App.MySnackbar.Danger(result!.Message ?? "");
                        }
                    }
                    catch (Exception ex)
                    {
                        App.MySnackbar.Danger(ex.Message, ex.Message);
                    }
                    finally
                    {
                        App.MyContentDialog.CloseLoading();
                    }
                });

                if (reslut == ContentDialogResult.Primary)
                {
                    await RefreshData();
                }

            }
        }


        public async Task RefreshData()
        {
            void fun(List<CorpusAdornWithTypeDto>? viewData)
            {
                if (viewData == null) return;

                if (!Application.Current.Dispatcher.CheckAccess())
                {
                    Application.Current.Dispatcher.Invoke(new Action(() => fun(viewData)));
                    return;
                }

                this.ViewData = viewData;
            }

            await App.MyContentDialog.ShowRingLoadingAsync(async () =>
            {
                try
                {
                    pagingDto.SearchField.Clear();
                    if (SearchTitle != null)
                    { pagingDto.SearchField.Add("Title", SearchTitle); }

                    if (selectedTypeIds.Count > 0)
                        pagingDto.SearchField.Add("SelectedTypeIds", string.Join(',', selectedTypeIds));

                    var data = await Dal.ListWithTypeAsync(pagingDto);

                    if (data.Success)
                    {
                        fun(data.Data);
                    }
                }
                catch (Exception ex)
                {
                    App.MySnackbar.Danger(ex.Message, ex.Message);
                }
                finally
                {
                    App.MyContentDialog.CloseLoading();
                }
            });
        }


        public async Task ShowDrawerAsync()
        {
            if (!App.Current.Dispatcher.CheckAccess())
            {
                await Application.Current.Dispatcher.Invoke(async () => await ShowDrawerAsync());
                return;
            }

            var drawerReturn = await App.MyDrawer.ShowDrawer<UcCorpusAdornTypeSelector>(obj =>
            {
                if (obj is IInitDataContextViewModel model)
                {
                    model.InitDataContext(new ClientInfrastructure.Dto.PageParameterDto { Model = selectedTypeIds });
                }
            });

            if (drawerReturn.Data is List<CorpusAdornTypeEntity> selected)
            {
                selectedTypeIds = selected.Select(x => x.Id).ToList();
                SelectedTypeTitles = string.Join(';', selected.Select(y => y.Title).ToList());

            }
            else
            {
                selectedTypeIds = [];
                SelectedTypeTitles = "";
            }

        }
    
    
    }
}
